package com.Aopxml.StaticProxy;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.Arrays;


/**
 * @author cc
 * @date 2021/8/13 17:46
 * @Description 1-4-2
 */

public class Transaction {
    /**
     * joinpoint：被拦截的方法，就是目标类那些方法
     * @author sosmcc
     * @param joinpoint
     */
    //前置增强，在目标的方法执行之前
    public void OpenAffair(JoinPoint joinpoint){
        //获取目标内的方法名
        String name = joinpoint.getSignature().getName();
        //获取方法里面的参数
        Object[] args = joinpoint.getArgs();
        System.out.println("开启事务....方法名:"+name+",参数是:"+ Arrays.toString(args));

    }
    //  02-返回通知：目标方法返回之后进行通知(如果目标方法有异常不会执行)
    public void closeAffair(JoinPoint joinPoint,Object o){
        String name = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("提交事务....方法名:"+name+",参数是:"+ Arrays.toString(args)+",返回值:"+o);

    }

    //     * 03-异常通知:在目标方法出现异常就会异常通知！
    public void myException(JoinPoint joinPoint,Exception ex){
        String name = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("出现异常方法是："+name+"异常方法的参数："+args);
        System.out.println("异常类型；"+ex.getMessage());
    }

   //      * 04-后置通知:目标方法返回之后进行通知(无论目标方法是否有异常都会执行) 类似Java中finnally
   public void finnallyAffair(JoinPoint joinPoint){
       String name = joinPoint.getSignature().getName();//被拦截的方法的方法名
       Object[] args = joinPoint.getArgs(); //被拦截的方法的参数
       System.out.println("关闭数据库资源...."+name+",参数是:"+ Arrays.toString(args));
   }

    /**
     * ProceedingJoinPoint只支持环绕通知
     * @param joinPoint
     * @return
     */
    public Object ArroundAdvice(ProceedingJoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();//拦截的方法名
        Object[] args = joinPoint.getArgs(); //获取方法参数
        Object result  =null;
        try {
            System.out.println("开启事务....方法名:"+name+",参数是:"+ Arrays.toString(args));
            result = joinPoint.proceed();
            System.out.println("提交事务....方法名:"+name+",参数是:"+ Arrays.toString(args)+",返回值:"+result);
        } catch (Throwable throwable) {
            System.out.println("出现异常方法是："+name+"异常方法的参数："+args);
            System.out.println("异常类型；"+throwable.getMessage());
            throwable.printStackTrace();
        }
        finally {
            System.out.println("关闭数据库资源...."+name+",参数是:"+ Arrays.toString(args));
        }
        return result;
    }
}
